package com.evaluity;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import shared.Constants;

import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;

public class Universities extends ListActivity {

	public ArrayList<University> getUniversitiesFromJSON(String JSON) {
		ArrayList<University> universities = new ArrayList<University>();
		try {
			//JSONObject Object = new JSONObject(JSON);
			JSONArray jsonArray = new JSONArray(JSON);
			for(int i = 0; i < jsonArray.length(); i++ ){
        		JSONObject jsonObject = jsonArray.getJSONObject(i);
        		String nom = jsonObject.getString("nombre");
        		String siglas = jsonObject.getString("siglas");
        		String region = jsonObject.getString("region");
        		
        		URL newurl = null;
				try {
					newurl = new URL(jsonObject.getString("logo"));
				} catch (MalformedURLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
        		
        		Bitmap logo = null;
        		try {
        			logo = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream()); 
        		}
        		catch (Exception e) {
        			System.out.println("Error carregant foto");
        		}
        		
        		universities.add(new University(nom, siglas, logo, region));
        	}
			return universities;
		} 
		catch (JSONException e) {
			e.printStackTrace();
			return null;
			//jsonLabel.setText("error");
		}
	}
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_universities);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		
		if(Build.VERSION.SDK_INT > 11) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        	
		Intent intent = getIntent();
		String unis = intent.getStringExtra(Constants.EXTRA_ACTIVITY);
		ArrayList<University> universities = getUniversitiesFromJSON(unis);
		
		setListAdapter(new MyCustomAdapterView(this, universities));
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
